package drds.server.sqlparser.parser;

/**
 * 解析公共类
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class SqlParser {

	protected final Lexer lexer;

	public SqlParser(String sql) {
		this(new Lexer(sql));
		this.lexer.nextMark();
	}

	public SqlParser(Lexer lexer) {
		this.lexer = lexer;
	}

	public final Lexer getLexer() {
		return lexer;
	}

	protected void acceptIdentifier(String text) {
		if (identifierEquals(text)) {
			lexer.nextMark();
		} else {
			setErrorPosotion(lexer.index());
			throw new ParserException("syntax error, expect " + text + ", actual " + lexer.getMark());
		}
	}

	protected boolean identifierEquals(String text) {
		return lexer.getMark() == Mark.IDENTIFIER && lexer.stringValue().equals(text);
	}

	protected void printError(Mark mark) {
		String arround;
		if (lexer.bufferStartIndex >= 0 && (lexer.sql.length() > lexer.bufferStartIndex + 30)) {
			if (lexer.bufferStartIndex - 5 > 0) {
				arround = lexer.sql.substring(lexer.bufferStartIndex - 5, lexer.bufferStartIndex + 30);
			} else {
				arround = lexer.sql.substring(lexer.bufferStartIndex, lexer.bufferStartIndex + 30);
			}

		} else if (lexer.bufferStartIndex >= 0) {
			if (lexer.bufferStartIndex - 5 > 0) {
				arround = lexer.sql.substring(lexer.bufferStartIndex - 5);
			} else {
				arround = lexer.sql.substring(lexer.bufferStartIndex);
			}
		} else {
			arround = lexer.sql;
		}

		throw new ParserException("syntax error, error in :'" + arround + "',expect " + mark + ", actual " + lexer.getMark() + " " + lexer.stringValue());
	}

	public void accept(Mark mark) {

		if (lexer.getMark() == mark) {
		} else {
			System.out.println("当前:" + lexer.mark + ",need:" + mark);
			if (lexer.mark == Mark.IDENTIFIER) {
				System.out.println("当前标识符的值是:" + lexer.stringValue);
			}
			setErrorPosotion(lexer.index());
			printError(mark);
		}
	}

	private int errorPosotion = -1;

	protected void setErrorPosotion(int errorPosotion) {
		if (errorPosotion > this.errorPosotion) {
			this.errorPosotion = errorPosotion;
		}
	}

}
